package top.chenyaohua;

import sun.misc.Service;
import top.chenyaohua.http.RequestHandler;
import top.chenyaohua.init.abstractInit.AbstractInitExecution;
import top.chenyaohua.utils.InitExecutionUtils;
import top.chenyaohua.utils.PropertieUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Hello world!
 *
 */

public class App 
{


    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(100,100,
                                                        60, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

    private static Properties properties = PropertieUtils.getProperties("app.properties");


    public static void main( String[] args ) {
        init();

        ServerSocket serverSocket = null;
        try {

            Integer port = Integer.valueOf(properties.getProperty("server.port"));
            serverSocket = new ServerSocket(port);

            while (!serverSocket.isClosed()){

                Socket socket = serverSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);

                threadPoolExecutor.execute(requestHandler);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            threadPoolExecutor.shutdown();
        }
    }

    /**
     * 初始化容器
     */
    private static void init () {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Runnable runnable = ()->{
            //获取spi类对象
            Iterator<AbstractInitExecution> providers = Service.providers(AbstractInitExecution.class);
            List<AbstractInitExecution> list = new ArrayList<>();
            while (providers.hasNext()) {
                AbstractInitExecution next = providers.next();
                list.add(next);
            }

            //排序先后执行
            Stream<AbstractInitExecution> sorted = list.stream().sorted(Comparator.comparing(AbstractInitExecution::getOrder));
            List<AbstractInitExecution> collect = sorted.collect(Collectors.toList());
            AbstractInitExecution abstractInitExecution = collect.get(0);
            InitExecutionUtils.set(collect);
            //启动top.chenyaohua.init.imp.DefaultInit 扫描\注册信息
            abstractInitExecution.init();
        };

        executorService.execute(runnable);

        executorService.shutdown();
    }
}
